package cn.antia.db;

import java.util.Map;

/**
 * User: Jair Shaw
 * Date: 2008-6-27
 * Time: 17:38:27
 */
public class SQLServerSQLGene extends AbstractSQLGene{
    public String composeSqlPage(String sql, String orderField, boolean isAsc, int page, int pageSize) {
        int start = (page - 1) * pageSize + 1;
        int end = start + pageSize;
        return composeSql(sql, orderField, isAsc, start, end);
    }

    public String composeSql(String sql, String orderField, boolean isAsc, int start, int end) {
        //order
        String order = new StringBuilder(" ORDER BY ").append(orderField).append(isAsc ? " ASC" : " DESC").toString();
        //rowNum statement
        String rowNum = new StringBuilder("ROW_NUMBER() OVER(").append(order).append(") AS rowNum").toString();
        //where statement
        String where = "WHERE rowNum BETWEEN " + start + " AND " + end;
        //join rownum statement
        sql = sqlInsertRowNum(sql, rowNum);
        //compose
        return new StringBuilder().append("SELECT * FROM (").append(sql).append(") AS MyTempTable ").append(where).toString();
    }

    /**
     * 将 rowNum 插入到 SQL 中间组成一个新的SQL
     * @param sql sql
     * @param rowNum    row number
     * @return new sql
     */
    private static String sqlInsertRowNum(String sql, String rowNum) {
        boolean isSQNormal = true;
        boolean isBracketNoraml = true;
        String UPPERSQL = sql.toUpperCase().trim();
        //confirm 'FROM' position
        int fromPosition = UPPERSQL.indexOf(" FROM ");
        for (int i = 0; i < sql.length(); i++) {
            String s = sql.substring(i, i + 1);
            if (isBracketNoraml) {
                if (s.equals("(")) {
                    isBracketNoraml = false;
                }
            } else if (s.equals(")")) {
                isBracketNoraml = true;
            }
            if (isSQNormal) {
                if (s.equals("'")) {
                    isSQNormal = false;
                }
            } else if (s.equals("'")) {
                isSQNormal = true;
            }
            if (fromPosition == i) {
                if (isSQNormal && isBracketNoraml) {
                    break;
                } else {
                    fromPosition = UPPERSQL.indexOf(" FROM ", i + 1);
                    if (fromPosition == -1) {
                        System.out.println(" error ----- ");
                    }
                }
            }
        }
        return new StringBuilder().append(sql.substring(0, fromPosition)).append(",").append(rowNum).append(sql.substring(fromPosition, sql.length())).toString();
    }

    public SqlParams whereStatement(Map<String, Object> conditions, boolean isExact) {
        return null;
    }
}
